﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Diagnostics;

public class ProtobufEditor {

    static List<string> paths = new List<string>();
    static List<string> files = new List<string>();


    /// <summary>
    /// 数据目录
    /// </summary>
    static string AppDataPath
    {
        get { return Application.dataPath.ToLower(); }
    }
    static string ServerRoot
    {
        get { return Application.dataPath.Replace("Client/Assets", "Server/"); }
    }
    static string PBPath
    {
        get { return AppDataPath + "/Scripts/Protobuf/"; }
    }

    static void Recursive(string path)
    {
        string[] names = Directory.GetFiles(path);
        string[] dirs = Directory.GetDirectories(path);
        foreach (string filename in names)
        {
            string ext = Path.GetExtension(filename);
            if (ext.Equals(".meta")) continue;
            files.Add(filename.Replace('\\', '/'));
        }
        foreach (string dir in dirs)
        {
            paths.Add(dir.Replace('\\', '/'));
            Recursive(dir);
        }
    }

    [MenuItem("Tool/Build Protobuf-net File")]
    public static void BuildPB2CSFile()
    {
        paths.Clear(); files.Clear(); Recursive(PBPath);

        string protogen = ServerRoot + "ProtoGen/protogen.exe";

        foreach (string f in files)
        {
            string ext = Path.GetExtension(f);
            if (!ext.Equals(".proto")) continue;

            string inName = Path.GetFileName(f);
            string outName = inName.Replace(".proto", ".cs");

            string outPath = AppDataPath + "/Scripts/Protobuf/" + outName;
            ProcessStartInfo info = new ProcessStartInfo();
            info.FileName = protogen;
            info.Arguments = " -i:" + inName + " -o:" + outPath;
            info.WindowStyle = ProcessWindowStyle.Hidden;
            info.UseShellExecute = true;
            info.WorkingDirectory = PBPath;
            info.ErrorDialog = true;
            UnityEngine.Debug.Log(info.FileName + " " + info.Arguments);

            Process pro = Process.Start(info);
            pro.WaitForExit();

            string copyPath = ServerRoot + "Server/Protobuf/" + Path.GetFileName(f).Replace(".proto", ".cs");
            File.Copy(outPath, copyPath, true);
        }
        AssetDatabase.Refresh();
    }

    [MenuItem("Tool/Copy Protocal")]
    public static void CopyProtocalFile()
    {
        string sourceFile = AppDataPath + "/Scripts/Network/Protocol.cs";
        string targetFile = ServerRoot + "/Server/Network/Protocal.cs";
        File.Copy(sourceFile,targetFile,true);

        UnityEngine.Debug.LogFormat("Copy file:{0}->{1}", sourceFile,targetFile);
    }
}
